package com.study.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.study.common.UserInfoDTO;
import com.study.convention.errorCode.BaseErrorCode;
import com.study.convention.exception.ClientException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.Calendar;
import java.util.Objects;


/**
 * @author canace
 * @version 1.0
 * @description jwt工具类
 * @date 2024/1/23 18:01
 */
@Component
@Slf4j
public class JwtUtils {

    /**
     * 定义系统标识头常量
     */
    private static final String HEADER_SYSTEM_KEY = "systemKeyHeader";

    /**
     * 根据用户名获取token
     * @param userInfoDTO 用户信息
     * @return token
     */
    public static String getToken(UserInfoDTO userInfoDTO){
        Calendar instance = Calendar.getInstance();
        // 令牌过期时间
        instance.add(Calendar.DATE, 1);
        JWTCreator.Builder builder = JWT.create();
        builder.withClaim("username", userInfoDTO.getUsername())
                .withClaim("userId", userInfoDTO.getUserId())
                .withClaim("realName", userInfoDTO.getRealName());
        return builder.withExpiresAt(instance.getTime()).sign(Algorithm.HMAC256(HEADER_SYSTEM_KEY));
    }

    /**
     * 校验token
     * @param token token
     * @return 成功返回用户名
     */
    public static DecodedJWT verifyToken(String token){
        if(!StringUtils.hasText(token)){
            throw new ClientException(BaseErrorCode.TOKEN_IS_NULL);
        }
        return JWT.require(Algorithm.HMAC256(HEADER_SYSTEM_KEY)).build().verify(token);
    }

}
